package com.ts.opengl

import android.content.Context
import android.opengl.GLES20
import com.ts.audiocamera.R
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import javax.microedition.khronos.opengles.GL

class ScreenFilter {

    var program=0;
    constructor(context:Context){
        //顶点着色器
        val vertexShader =readRawTextFile(context, R.raw.camera_vert)
        val vShader=GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);

        GLES20.glShaderSource(vShader,vertexShader)

        GLES20.glCompileShader(vShader);

        var status=IntArray(1)

        GLES20.glGetShaderiv(vShader,GLES20.GL_COMPILE_STATUS,
            status, 0)

        check(status[0] == GLES20.GL_TRUE) {
            //失败
            "load vertex shader:" + GLES20.glGetShaderInfoLog(vShader)
        }
        //片着色器

        val fragShader =readRawTextFile(context, R.raw.camera_frag)
        val fragvShader=GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);

        GLES20.glShaderSource(fragvShader,fragShader)

        GLES20.glCompileShader(vShader);

         status=IntArray(1)

        GLES20.glGetShaderiv(vShader,GLES20.GL_COMPILE_STATUS, status, 0)
        check(status[0] == GLES20.GL_TRUE) {
            //失败
            "load vertex shader:" + GLES20.glGetShaderInfoLog(vShader)
        }


        program=GLES20.glCreateProgram();

        GLES20.glAttachShader(program,vShader);

        GLES20.glAttachShader(program,fragvShader)

        GLES20.glLinkProgram(program)

    }



    fun readRawTextFile(context:Context , rawId:Int ) :String{
        val `is`: InputStream = context.resources.openRawResource(rawId)
        val br = BufferedReader(InputStreamReader(`is`))
        var line: String?
        val sb = StringBuilder()
        try {
            while ((br.readLine().also { line = it }) != null) {
                sb.append(line)
                sb.append("\n")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            br.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return sb.toString()
    }


}